package com.dreamoo.common.threadlocal;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 山顶洞人郑某
 * @className BaseParameterHolder.java ThreadLocal线程绑定工具
 * @date 2025 05 05
 */
public class BaseParameterHolder {

    /**
     * 线程绑定参数
     */
   private static final TransmittableThreadLocal<Map<String,String>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    /**
     * 获取线程局部变量
     * @param key key
     * @param clazz 变量类型
     * @return
     * @param <T>
     */
   public static <T> T get(String key,Class<T> clazz) {
       Map<String, String> map = THREAD_LOCAL.get();
       if ( !MapUtil.isEmpty(map) ) {
           String s = map.get(key);
           if (clazz == String.class) {
               return (T) s;
           }
           if (!StringUtils.isEmpty(s)) {
               return JSONUtil.toBean(s, clazz);
           }
       }
       return null;
   }

    /**
     * 获取局部所有参数
     * @return
     */
   public static Map<String,String > getAll() {
       return THREAD_LOCAL.get();
   }
    /**
     * 设置局部变量
     * @param key key
     * @param value 设置的值
     * @param <T> 泛型
     */
   public static<T> void set(String key, T value) {
       Map<String, String> map = THREAD_LOCAL.get();
       if ( MapUtil.isEmpty(map) ) {
           map = new HashMap<>(8);
       }
       map.put(key,JSONUtil.toJsonStr(value));
       THREAD_LOCAL.set(map);
   }

   public static void remove() {
       THREAD_LOCAL.remove();
   }

    public static void main(String[] args) {

        User user = new User();
        user.setName("张三");
        user.setSex("男");
        set("user",user);
       
    }

    /**
     * 设置所有参数
     * @param paramter 局部线程的参数
     */
    public static void setAll(Map<String, String> paramter) {
        remove();
        THREAD_LOCAL.set(paramter);
    }

    @Data
    static class User{
       String name;
       String sex;
    }
}
